import { CONST_SingleResourceAction, type SingleResourceActionType } from "@packages/shared";
import type mongoose from "mongoose"
import z from "zod";
import { infoLog } from "../../utils/log";

export const ResourceAction = {
    READ: [
        CONST_SingleResourceAction.LIST, CONST_SingleResourceAction.ONE
    ],
    WRITE: [
        CONST_SingleResourceAction.CREATE, CONST_SingleResourceAction.UPDATE, CONST_SingleResourceAction.DELETE
    ],
    ALL: [
        CONST_SingleResourceAction.LIST, CONST_SingleResourceAction.ONE,
        CONST_SingleResourceAction.CREATE, CONST_SingleResourceAction.UPDATE, CONST_SingleResourceAction.DELETE
    ]
} as const
export type ResourceActionType = typeof ResourceAction[keyof typeof ResourceAction]


export type ResourceConfig = {
    /** 资源描述 */
    description: string,
    /** 资源Model */
    model: mongoose.Model<any>,
    /** 允许的动作 */
    action: SingleResourceActionType[];
    /** 校验器 */
    validator: {
        createValid: z.ZodObject,
        updateValid: z.ZodObject,
        deleteValid: z.ZodObject,
        // oneValid: z.ZodAny,
        // listValid: z.ZodAny
    }
}


const resources = new Map<string, ResourceConfig>()

export const registerResource = (resource: ResourceConfig | ResourceConfig[]) => {

    if (Array.isArray(resource)) {
        resource.forEach(item => {
            resources.set(item.model.modelName, item)
        })
    } else {
        resources.set(resource.model.modelName, resource)
        infoLog(`注册资源:${resource.model.modelName}`)
    }
}

export const getResourceByName = (name: string) => {
    return resources.get(name)
}

export const generateResources = () => {
    return [...resources.keys()]
}